﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Security;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin.Security;
using Owin;

namespace CloudStorageLight.SampleWeb.Models
{
    public static class BasicAuthenticateUtil
    {
        public async static Task<bool> Authenticate(HttpApplication httpApp)
        {
            string authString = httpApp.Request.Headers["Authorization"];
            bool auth = false;

            if (!string.IsNullOrEmpty(authString) && authString.IndexOf("Basic", 0) == 0)
            {
                string encodedString = authString.Substring(6);
                byte[] decodedBytes = Convert.FromBase64String(encodedString);
                string decodedString = new ASCIIEncoding().GetString(decodedBytes);
                string[] arrSplited = decodedString.Split(new char[] { ':' });
                string username = arrSplited[0];
                string password = arrSplited[1];
                if (await AuthenticateUser(username, password))
                {
                    httpApp.Context.User = new GenericPrincipal(new GenericIdentity(username), null);
                    FormsAuthentication.SetAuthCookie(username, false);
                }
                else
                {
                    httpApp.Response.Clear();
                    httpApp.Response.StatusCode = 401;
                    httpApp.Response.StatusDescription = "Unauthorized";
                    httpApp.Response.Write("<html><head><title>401 Unauthorized</title></head><body><h1>401 Access Denied</h1></body></html>");
                    auth = true;
                }
            }
            return auth;
        }

        public static void AddUnauthorizedHeader(HttpApplication httpApp)
        {
            httpApp.Response.AppendHeader("WWW-Authenticate", "Basic Realm=Authentication");
        }

        private async static Task<bool> AuthenticateUser(string username, string password)
        {
            var ctx = new HttpContextWrapper(HttpContext.Current);
            var manager = ctx.GetOwinContext().GetUserManager<ApplicationUserManager>();
            var user = await manager.FindAsync(username, password);
            if (user != null)
            {
                return true;

            }
            else
            {
                return false;
            }

        }

    }

}